#!/usr/bin/env python
import email
import md5

from sessions import Session
from time import gmtime, strftime

from google.appengine.ext.webapp import RequestHandler
from google.appengine.api import users, images
from google.appengine.ext import db

from templates import run, render, redirect, out
from models import UserActions,Photos,EmailActionUpdate, Friends


class Home(RequestHandler):
	
	session = Session()
	
	def get(self):
		user = users.get_current_user()		
		ua = UserActions()
		userActions = ua.gql("WHERE email = :1 ORDER BY updated DESC", user)

		p = Photos()
		profilepic = p.gql("WHERE email = :1", user.email())

		friends = Friends.all()	
		friends.filter('email = ', user)
		friends.filter('approved = ', 1)
		
		pendingfriends = Friends.all()
		pendingfriends.filter('friendEmail = ', user.email())
		pendingfriends.filter('approved = ', 0)
		
		emailaddy = EmailActionUpdate.gql("WHERE email = :1", user.email()).get()
        

		if emailaddy:
			emailAddress = "%s@noisewater.net" % emailaddy.passwd
		else:
			emailAddress = None

			
		if self.session['rippleError']:
			error = self.session['rippleError']
			del(self.session['rippleError'])
		else:
			error = None
		
		if self.session['friendemail']:
			friendErrorEmail = self.session['friendemail']
			del(self.session['friendemail'])
		else:
			friendErrorEmail = None

		if self.session['friendname']:
			friendErrorName = self.session['friendname']
			del(self.session['friendname'])
		else:
			friendErrorName = None



		render(self, 'home.html', values=    {'loglink': users.create_logout_url("/"),
											  'loglabel': 'logout',
											  'nick':user.nickname(),
											  'userActions' : userActions,
											  'emailAddress':emailAddress,
											  'friends': friends,
											  'pendingfriends':pendingfriends,
											  'error':error,
											  'friendErrorEmail':friendErrorEmail,
											  'friendErrorName': friendErrorName})

	def post(self):
		if not self.request.get('whatyoudo'):
			self.session['rippleError'] = 'You must enter a ripple before you can update'
			redirect(self,'/home')
		else:
			user = users.get_current_user()
			ua = UserActions(actions=self.request.get('whatyoudo'), email=users.get_current_user(), nickname=user.nickname())
			ua.put()
			redirect(self, '/home')


class Photo(RequestHandler):
	session = Session()
	def get(self): 
		user = users.get_current_user()

		if self.session['photoError']:
			error = self.session['photoError']
			del(self.session['photoError'])
		else:
			error = None

		render(self, 'photo.html', values={ 'loglink': users.create_logout_url("/"), 
											'loglabel':'logout', 
											'usr':user.nickname(),
											'error': error})

	def post(self):
		user = users.get_current_user()

		if not self.request.get('userpic'):
			self.session['photoError'] = 'You must select a picture'
			redirect(self, '/photo')
		else:
			profile = images.resize(self.request.get('userpic'), 75, 75)
			thumbnail = images.resize(self.request.get('userpic'), 30,30)

			photo = Photos.gql("WHERE email = :1", user.email()).get()
			
			if photo:
				photo.profile = db.Blob(profile)
				photo.thumbnail = db.Blob(thumbnail)
				photo.put()
			else:
				photo = Photos()
				photo.email = user.email()
				photo.nickname = user.nickname()
				photo.profile = db.Blob(profile)
				photo.thumbnail = db.Blob(thumbnail)
				photo.put()

			redirect(self, '/home')


class Feed(RequestHandler):
    def get(self):
        uri = self.request.uri.split('/')[4].replace('%40','@')
        ua = UserActions.all()
        ua.filter('nickname = ', uri)
        ua.order('-updated')
        current = ua.fetch(1)
        render(self, 'feed.html', {'current':current, 'usr':uri})

class Rss(RequestHandler):
    def get(self):
        uri = self.request.uri.split('/')[4].replace('%40','@')
        ua = UserActions.all()
        ua.filter('nickname = ', uri)
        ua.order('-updated')
        current = ua.fetch(10)
        render(self, 'rss.html', {'current':current, 'usr':uri})

class Privacy(RequestHandler):
    def get(self):
        uri = self.request.uri.split('/')[3]
        ua = UserActions.all()
        ua.filter('nickname = ', uri)
        ua.order('-updated')
        current = ua.fetch(10)
        render(self, 'privacy.html', {'current':current, 'usr':uri})




def main():
    run([('/home', Home),
         ('/feed/.*', Feed),
         ('/rss/.*', Rss),
         ('/photo', Photo),
         ('/privacy',Privacy)])

if __name__ == '__main__': main()
